package demo.sort;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author lingyun.wang on @date 2021/12/27
 */
public class SortUtils {
    public static <T> List<T> sort(List<T> list , List<SortBO> sortFields){
        Comparator<T> thisComparator = null;
        for (SortBO sortField : sortFields) {
            Comparator sortComparator = Comparator.naturalOrder();
            if("desc".equals(sortField.getSort())){
                sortComparator = Comparator.reverseOrder();
            }
            Function sortFieldFunc = newSortFunction(sortField.getField());

            if(null==thisComparator){
                thisComparator = Comparator.comparing(sortFieldFunc,sortComparator);
            }else {
                thisComparator = thisComparator.thenComparing(sortFieldFunc,sortComparator);
            }
        }
        list = list.stream().sorted(thisComparator).collect(Collectors.toList());
        return list;
    }

    private static  <T,U> Function newSortFunction(String sortField){
        return (p) ->{
            if(p instanceof Map){
                return ((Map<String,Object>)p).get(sortField);
            }
            return p;
        };
    }
}
